package com.up.vms.interfaces.rest.utils;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.Map.Entry;

import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpDelete;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpPut;
import org.apache.http.client.methods.HttpRequestBase;
import org.apache.http.client.protocol.HttpClientContext;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.util.StreamUtils;

@Service
public class HttpClientUtil {
    private static final Logger log = LoggerFactory.getLogger(HttpClientUtil.class);
    private static final int TIME_OUT = 10000;
    private static CloseableHttpClient httpClient = null;
    private static final String DEFAULT_CHARSET_STR = "utf-8";
    private static final Charset DEFAULT_CHAR_SET = Charset.forName("UTF-8");

    public HttpClientUtil() {
    }

    private static synchronized CloseableHttpClient getHttpClientSync() {
        if (httpClient == null) {
            httpClient = HttpClientFactory.getPooledClient();
        }

        return httpClient;
    }

    public static CloseableHttpClient getHttpClient() {
        return httpClient == null ? getHttpClientSync() : httpClient;
    }

    public HttpClientResponseMsg postMap(HttpClientEntity entity) {
        HttpPost httpPost = new HttpPost(entity.getUrl());
        config(httpPost);
        setPostParams(httpPost, entity.getContentMap());
        HttpClientResponseMsg msg;
        if ("FILE".equals(entity.getResponseFormat())) {
            msg = getFile(httpPost);
        } else {
            msg = getString(httpPost);
        }

        return msg;
    }

    public HttpClientResponseMsg post(HttpClientEntity entity) {
        HttpPost httpPost = new HttpPost(entity.getUrl());
        if (StringUtils.isBlank(entity.getContextType())) {
            entity.setContextType("application/x-www-form-urlencoded");
        }

        setPostContent(httpPost, entity);
        config(httpPost);
        return getString(httpPost);
    }

    public HttpClientResponseMsg put(HttpClientEntity entity) {
        HttpPut httpPut = new HttpPut(entity.getUrl());
        if (StringUtils.isBlank(entity.getContextType())) {
            entity.setContextType("application/x-www-form-urlencoded");
        }

        setPutContent(httpPut, entity);
        config(httpPut);
        return getString(httpPut);
    }

    private static void setPostContent(HttpPost httpPost, HttpClientEntity httpClientEntity) {
        LinkedHashMap<String, String> headers = httpClientEntity.getHeaders();
        if (headers != null && headers.size() > 0) {
            Iterator var3 = headers.entrySet().iterator();

            while(var3.hasNext()) {
                Entry<String, String> entry = (Entry)var3.next();
                httpPost.setHeader((String)entry.getKey(), (String)entry.getValue());
            }
        }

        StringEntity myEntity = new StringEntity(httpClientEntity.getData(), "utf-8");
        myEntity.setContentType(httpClientEntity.getContextType());
        httpPost.setEntity(myEntity);
    }

    private static void setPutContent(HttpPut httpPut, HttpClientEntity httpClientEntity) {
        LinkedHashMap<String, String> headers = httpClientEntity.getHeaders();
        if (headers != null && headers.size() > 0) {
            Iterator var3 = headers.entrySet().iterator();

            while(var3.hasNext()) {
                Entry<String, String> entry = (Entry)var3.next();
                httpPut.setHeader((String)entry.getKey(), (String)entry.getValue());
            }
        }

        StringEntity myEntity = new StringEntity(httpClientEntity.getData(), "utf-8");
        myEntity.setContentType(httpClientEntity.getContextType());
        myEntity.setContentEncoding("utf-8");
        httpPut.setEntity(myEntity);
    }

    public static String get(String url) {
        HttpGet httpGet = new HttpGet(url);
        config(httpGet);
        HttpClientResponseMsg msg = getString(httpGet);
        return msg.getResult();
    }

    public HttpClientResponseMsg get(HttpClientEntity entity) {
        HttpGet httpGet = new HttpGet(entity.getUrl());
        LinkedHashMap<String, String> headers = entity.getHeaders();
        if (headers != null && headers.size() > 0) {
            Iterator var4 = headers.entrySet().iterator();

            while(var4.hasNext()) {
                Entry<String, String> entry = (Entry)var4.next();
                httpGet.setHeader((String)entry.getKey(), (String)entry.getValue());
            }
        }

        config(httpGet);
        return getString(httpGet);
    }

    public HttpClientResponseMsg delete(HttpClientEntity entity) {
        HttpDelete httpDelete = new HttpDelete(entity.getUrl());
        LinkedHashMap<String, String> headers = entity.getHeaders();
        if (headers != null && headers.size() > 0) {
            Iterator var4 = headers.entrySet().iterator();

            while(var4.hasNext()) {
                Entry<String, String> entry = (Entry)var4.next();
                httpDelete.setHeader((String)entry.getKey(), (String)entry.getValue());
            }
        }

        config(httpDelete);
        return getString(httpDelete);
    }

    private static HttpClientResponseMsg getFile(HttpRequestBase request) {
        CloseableHttpResponse response = null;
        HttpClientResponseMsg httpClientResponseMsg = new HttpClientResponseMsg();

        try {
            CloseableHttpClient httpClient = getHttpClient();
            response = httpClient.execute(request, HttpClientContext.create());
            int statusCode = response.getStatusLine().getStatusCode();
            HttpEntity entity = response.getEntity();
            File desc = new File("/home/vms/down" + File.separator + "download.zip");
            File folder = desc.getParentFile();
            folder.mkdirs();
            InputStream is = entity.getContent();
            Throwable var9 = null;

            try {
                OutputStream os = new FileOutputStream(desc);
                Throwable var11 = null;

                try {
                    StreamUtils.copy(is, os);
                } catch (Throwable var49) {
                    var11 = var49;
                    throw var49;
                } finally {
                    if (os != null) {
                        if (var11 != null) {
                            try {
                                os.close();
                            } catch (Throwable var48) {
                                var11.addSuppressed(var48);
                            }
                        } else {
                            os.close();
                        }
                    }

                }
            } catch (Throwable var51) {
                var9 = var51;
                throw var51;
            } finally {
                if (is != null) {
                    if (var9 != null) {
                        try {
                            is.close();
                        } catch (Throwable var47) {
                            var9.addSuppressed(var47);
                        }
                    } else {
                        is.close();
                    }
                }

            }

            EntityUtils.consume(entity);
            httpClientResponseMsg.setResult(desc.getPath());
            httpClientResponseMsg.setStatusCode(statusCode);
        } catch (Exception var53) {
            log.error("" + var53.getMessage(), var53);
        } finally {
            releaseIOStream(request, response);
        }

        return httpClientResponseMsg;
    }

    public static void releaseIOStream(HttpRequestBase request, CloseableHttpResponse response) {
        try {
            if (response != null) {
                response.close();
            }

            if (request != null) {
                request.releaseConnection();
            }
        } catch (IOException var3) {
            log.error("" + var3.getMessage(), var3);
        }

    }

    private static HttpClientResponseMsg getString(HttpRequestBase request) {
        CloseableHttpResponse response = null;
        HttpClientResponseMsg httpClientResponseMsg = new HttpClientResponseMsg();

        try {
            CloseableHttpClient httpClient = getHttpClient();
            response = httpClient.execute(request, HttpClientContext.create());
            int statusCode = response.getStatusLine().getStatusCode();
            HttpEntity entity = response.getEntity();
            String result = EntityUtils.toString(entity, DEFAULT_CHAR_SET);
            EntityUtils.consume(entity);
            httpClientResponseMsg.setResult(result);
            httpClientResponseMsg.setStatusCode(statusCode);
        } catch (Exception var10) {
            log.error("" + var10.getMessage(), var10);
        } finally {
            releaseIOStream(request, response);
        }

        return httpClientResponseMsg;
    }

    private static void setPostParams(HttpPost httPost, Map<String, Object> params) {
        List<NameValuePair> nvps = new ArrayList();
        Set<String> keySet = params.keySet();
        Iterator var4 = keySet.iterator();

        while(var4.hasNext()) {
            String key = (String)var4.next();
            nvps.add(new BasicNameValuePair(key, params.get(key).toString()));
        }

        try {
            httPost.setEntity(new UrlEncodedFormEntity(nvps, "UTF-8"));
        } catch (UnsupportedEncodingException var6) {
            log.error("" + var6.getMessage(), var6);
        }

    }

    private static void config(HttpRequestBase httpRequestBase) {
        RequestConfig requestConfig = RequestConfig.custom().setConnectionRequestTimeout(10000).setConnectTimeout(10000).setSocketTimeout(10000).build();
        httpRequestBase.setConfig(requestConfig);
    }
}
